<template>
	<view class="container">
		<uni-load-more v-if="loading" status="loading" iconType="circle"></uni-load-more>

		<!-- 单选日历 -->
		<uni-calendar :lunar="false" @change="handleDateChange" :date="currentDate" :selected="selectedDates"
			@monthSwitch="handleMonthSwitch" :showMonth="false" mode="date">
		</uni-calendar>

		<!-- 新增复制排班按钮 -->
		<view class="copy-btn" @click="showCopyModal">
			<text class="iconfont icon-copy"></text> 复制排班
		</view>

		<view class="duty-section">
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="tab.type" :class="['tab', activeTab === index ? 'active' : '']"
					@click="switchTab(index)">
					<text class="group-name">{{ tab.name }}（{{ tab.selected }}）</text>
					<text v-if="tabs.length > 1" class="delete-btn" @click.stop="deleteGroup(index)">×</text>
				</view>

				<view class="tab add-btn" @click="addGroup">
					<text class="iconfont icon-add">+</text> 添加组
				</view>

				<view class="tab edit-btn" @click="editAllGroupNames">
					<text class="iconfont icon-edit"></text> 编辑
				</view>
			</view>

			<swiper :current="activeTab" @change="onSwiperChange" :style="{ height: swiperHeight + 'px' }">
				<swiper-item v-for="tab in tabs" :key="tab.type">
					<scroll-view scroll-y style="max-height: 400rpx; overflow-y: auto;">
						<view class="staff-grid">
							<button v-for="driver in getCurrentGroup(tab.type)" :key="driver.id" :class="[
									'staff-btn',
									driver.isSelected ? 'selected' : '',
									driver.isConflict ? 'conflict' : ''
								]" :disabled="driver.isConflict" @click="!driver.isConflict && toggleSelection(driver, tab.type)">
								{{ driver.name }}
							</button>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>

		<view class="footer">
			<uni-fab ref="fab" :pattern="pattern" horizontal="right" vertical="bottom" @fabClick="handleSubmit" />
		</view>

		<!-- 自定义编辑弹窗 -->
		<uni-popup ref="editPopup" type="dialog">
			<view class="edit-popup">
				<view class="popup-header">
					<text>编辑组名</text>
					<text class="iconfont icon-close" @click="closeEditPopup"></text>
				</view>
				<view class="popup-body">
					<view v-for="(tab, index) in tabs" :key="index" class="group-input">
						<text class="group-label">第{{ index+1 }}组：</text>
						<input class="uni-input" v-model="tab.name" @focus="onInputFocus" @blur="onInputBlur" />
					</view>
				</view>
				<view class="popup-footer">
					<button class="btn cancel" @click="closeEditPopup">取消</button>
					<button class="btn confirm" @click="saveGroupNames">保存</button>
				</view>
			</view>
		</uni-popup>

		<uni-calendar ref="calendar" class="uni-calendar--hook" :clear-date="true" :insert="false" :lunar="false" range
			@confirm="copyDutyToDates" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pattern: {
					icon: "checkmarkempty"
				},
				loading: false,
				currentDate: '',
				selectedDates: [], // 选中日期集合
				activeTab: 0,
				swiperHeight: 300,
				tabs: [{
						name: 'A组',
						type: 'group1',
						selected: 0
					},
					{
						name: 'B组',
						type: 'group2',
						selected: 0
					},
					{
						name: 'C组',
						type: 'group3',
						selected: 0
					},
					{
						name: 'D组',
						type: 'group4',
						selected: 0
					}
				],
				drivers: [],
				scheduleData: {}, // key: date, value: { groups: [] }

				// [新增] 用于跟踪被修改过的日期，使用 Set 可以自动去重
				modifiedDates: new Set(),

				// 新增字段：用于复制排班
				copyTargetDates: [], // 要复制到的目标日期
			};
		},
		computed: {
			getCurrentGroup() {
				return (type) => {
					const date = this.currentDate;
					const currentGroups = this.scheduleData[date]?.groups || this.getDefaultGroups();

					const currentGroup = currentGroups.find(g => g.groupType === type) || {
						groupType: type,
						groupName: this.tabs.find(t => t.type === type)?.name || `${type}组`,
						members: []
					};

					return this.drivers.map(d => {
						const isSelected = currentGroup.members.some(m => m.id === d.id);
						const isConflict = currentGroups.some(group => group.groupType !== type &&
							group.members.some(m => m.id === d.id));

						return {
							...d,
							isSelected,
							isConflict
						};
					});
				};
			}
		},
		watch: {
			currentDate(newDate) {
				this.updateTabStats();
			}
		},
		created() {
			this.tabs = this.initializeTabs();
			this.initData();
			this.loadDriverData();
		},
		mounted() {
			this.tabs = this.initializeTabs();
			this.calculateSwiperHeight();
		},
		methods: {
			isValidDate(dateString) {
				const reg = /^\d{4}-\d{2}-\d{2}$/;
				return reg.test(dateString);
			},
			initData() {
				const today = this.getDateString(new Date());
				this.currentDate = today;
				if (!this.scheduleData[today]) {
					this.$set(this.scheduleData, today, {
						groups: this.getDefaultGroups()
					});
				}
				this.loadDutyData(today);
			},

			getDefaultGroups() {
				return this.tabs.map(tab => ({
					groupType: tab.type,
					groupName: tab.name,
					members: []
				}));
			},

			async loadDriverData() {
				try {
					const obj = uniCloud.importObject('driver');
					const res = await obj.getDriverList();

					if (res.code === 0) {
						this.drivers = res.data.map(d => ({
							id: d._id,
							name: d.name,
							mobile: d.mobile || '',
							group: d.groupType || 'group1'
						}));
					} else {
						uni.showToast({
							title: '司机数据加载失败',
							icon: 'none'
						});
					}
				} catch (e) {
					//console.error('加载司机出错:', e);
				}
			},

			async loadDutyData(selectedDate) {
				const [year, month] = selectedDate.split('-');
				const startDate = `${year}-${month}-01`;
				const endDate = `${year}-${month}-${new Date(year, month, 0).getDate()}`;

				this.loading = true;
				try {
					const obj = uniCloud.importObject('duty');
					const res = await obj.getDutyDriver({
						startDate,
						endDate
					});

					if (res.code === 0) {
						res.data.forEach(item => {
							const date = item.data?.date;
							if (!this.isValidDate(date)) return;

							const groups = item.data?.groups || this.getDefaultGroups();
							this.$set(this.scheduleData, date, {
								groups
							});
						});

						this.selectedDates = res.data
							.filter(item => this.isValidDate(item.data.date))
							.map(item => ({
								date: item.data.date,
								info: '已排班'
							}));
					} else {
						uni.showToast({
							title: '排班数据加载失败',
							icon: 'none'
						});
					}
				} catch (e) {
					//console.error('加载排班出错:', e);
				} finally {
					this.loading = false;
					this.updateTabStats();
				}
			},

			editAllGroupNames() {
				this.$refs.editPopup.open();
			},

			closeEditPopup() {
				this.$refs.editPopup.close();
			},

			saveGroupNames() {
				uni.showLoading({
					title: '保存中'
				});
				setTimeout(() => {
					// [修改] 当组名变化时，将所有受影响的日期标记为已修改
					Object.keys(this.scheduleData).forEach(date => {
						this.scheduleData[date].groups.forEach(group => {
							const tab = this.tabs.find(t => t.type === group.groupType);
							if (tab && group.groupName !== tab.name) {
								group.groupName = tab.name;
								this.modifiedDates.add(date); // 标记日期
							}
						});
					});
					uni.hideLoading();
					this.closeEditPopup();
					uni.showToast({
						title: '保存成功，请记得提交',
						icon: 'success'
					});
				}, 500);
			},

			toggleSelection(driver, groupType) {
				const date = this.currentDate;
				const currentGroups = this.scheduleData[date]?.groups || this.getDefaultGroups();

				const currentGroup = currentGroups.find(g => g.groupType === groupType);

				const conflictGroup = currentGroups.find(group => group.groupType !== groupType &&
					group.members.some(m => m.id === driver.id));

				if (conflictGroup) {
					uni.showToast({
						title: `${driver.name} 已被其他组选择`,
						icon: 'none'
					});
					return;
				}

				const index = currentGroup.members.findIndex(m => m.id === driver.id);
				if (index === -1) {
					currentGroup.members.push({
						...driver
					});
				} else {
					currentGroup.members.splice(index, 1);
				}

				this.$set(this.scheduleData, date, {
					groups: currentGroups
				});

				// [修改] 将当前日期添加到已修改集合中
				this.modifiedDates.add(date);

				this.updateTabStats();
			},

			async handleSubmit() {
				// [修改] 检查是否有被修改的数据
				if (this.modifiedDates.size === 0) {
					uni.showToast({
						title: '没有需要提交的修改',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '提交确认',
					// [修改] 提示用户将要提交的变更数量
					content: `确定提交 ${this.modifiedDates.size} 天的排班变更数据？`,
					success: async (res) => {
						if (res.confirm) {
							this.loading = true;
							try {
								// [修改] 只从 modifiedDates 中提取需要提交的数据
								const payloadData = Array.from(this.modifiedDates).map(date => ({
									date,
									groups: this.scheduleData[date].groups
								}));

								if (payloadData.length === 0) {
									uni.showToast({
										title: '没有数据可提交',
										icon: 'none'
									});
									this.loading = false;
									return;
								}

								const obj = uniCloud.importObject('duty');
								const result = await obj.updateDutyDriver({
									data: payloadData
								});

								if (result.code === 0) {
									uni.showToast({
										title: '提交成功',
										icon: 'success'
									});
									// [修改] 提交成功后，清空已修改日期的集合
									this.modifiedDates.clear();
								} else {
									uni.showToast({
										title: result.msg || '提交失败',
										icon: 'none'
									});
								}
							} catch (e) {
								//console.error('提交错误:', e);
								uni.showToast({
									title: '网络错误',
									icon: 'none'
								});
							} finally {
								this.loading = false;
							}
						}
					}
				});
			},

			getDateString(date) {
				const y = date.getFullYear();
				const m = String(date.getMonth() + 1).padStart(2, '0');
				const d = String(date.getDate()).padStart(2, '0');
				return `${y}-${m}-${d}`;
			},

			handleDateChange(e) {
				let dates = [];

				if (!e || !e.fulldate) {
					return;
				}

				const date = e.fulldate;
				if (this.isValidDate(date)) {
					dates = [date];
				}

				if (dates.length > 0) {
					this.currentDate = dates[0];
				}

				this.$nextTick(() => {
					this.updateTabStats();
				});
			},
			handleMonthSwitch(e) {
				const year = e.year;
				const month = String(e.month).padStart(2, '0');
				const day = '01';
				const selectedDateStr = `${year}-${month}-${day}`;
				this.loadDutyData(selectedDateStr)
			},

			showCopyModal() {
				this.$refs.calendar.open()
			},

			copyDutyToDates(e) {
				let dates = [];

				if (e.range.data && e.range.data.length > 0) {
					dates = [...e.range.data];
				} else {
					dates = [e.fulldate];
				}

				this.copyTargetDates = [...new Set(dates.filter(date => date !== this.currentDate))];

				if (this.copyTargetDates.length === 0) {
					uni.showToast({
						title: '请至少选择一个目标日期',
						icon: 'none'
					});
					return;
				}

				if (!this.scheduleData[this.currentDate]?.groups) {
					uni.showToast({
						title: '请选择一个有排班的日期作为复制对象',
						icon: 'none'
					});
					return;
				}

				const sourceData = this.scheduleData[this.currentDate]?.groups || this.getDefaultGroups();

				this.copyTargetDates.forEach(date => {
					if (!this.scheduleData[date]) {
						this.$set(this.scheduleData, date, {
							groups: JSON.parse(JSON.stringify(sourceData))
						});
					} else {
						this.scheduleData[date].groups = JSON.parse(JSON.stringify(sourceData));
					}
					// [修改] 将被复制到的目标日期也添加到已修改集合中
					this.modifiedDates.add(date);
				});

				uni.showToast({
					title: '复制成功，请记得提交',
					icon: 'success'
				});
			},

			updateTabStats() {
				const date = this.currentDate;
				const data = this.scheduleData[date]?.groups || this.getDefaultGroups();

				this.tabs = this.tabs.map(tab => {
					const group = data.find(g => g.groupType === tab.type);
					const selectedCount = group?.members?.length || 0;
					return {
						...tab,
						selected: selectedCount
					};
				});
			},

			switchTab(index) {
				this.activeTab = index;
			},

			onSwiperChange(e) {
				const index = e.detail.current;
				// Make sure the index is within the valid range
				if (index >= 0 && index < this.tabs.length) {
					this.activeTab = index;
				} else if (this.tabs.length > 0) {
					// Fallback to last tab if index is out of bounds
					this.activeTab = this.tabs.length - 1;
				} else {
					this.activeTab = 0;
				}
			},

			calculateSwiperHeight() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.duty-section').boundingClientRect(data => {
					this.swiperHeight = data.height - 50;
				}).exec();
			},

			onInputFocus() {
				if (uni.getSystemInfoSync().platform === 'H5') {
					this.$nextTick(() => {
						window.scrollTo(0, document.body.scrollHeight);
					});
				}
			},

			onInputBlur() {},

		initializeTabs() {
			return [
				{
					name: 'A组',
					type: 'group1',
					selected: 0
				},
				{
					name: 'B组',
					type: 'group2',
					selected: 0
				},
				{
					name: 'C组',
					type: 'group3',
					selected: 0
				},
				{
					name: 'D组',
					type: 'group4',
					selected: 0
				}
			];
		},

		addGroup() {
			const nextIndex = this.tabs.length + 1;
			const nextLetter = String.fromCharCode(64 + nextIndex); // 65 is 'A', so 64 + 1 = 65 = 'A'
			const newGroup = {
				name: `${nextLetter}组`,
				type: `group${nextIndex}`,
				selected: 0
			};
			
			this.tabs.push(newGroup);
			
			// Update the scheduleData for the current date to include the new group
			if (this.scheduleData[this.currentDate]) {
				const currentGroups = this.scheduleData[this.currentDate].groups;
				if (!currentGroups.some(g => g.groupType === newGroup.type)) {
					currentGroups.push({
						groupType: newGroup.type,
						groupName: newGroup.name,
						members: []
					});
				}
			}
			
			// Switch to the new tab
			this.activeTab = this.tabs.length - 1;
		},

		deleteGroup(index) {
			if (this.tabs.length <= 1) {
				uni.showToast({
					title: '至少保留一个组',
					icon: 'none'
				});
				return;
			}

			uni.showModal({
				title: '确认删除',
				content: `确定要删除 ${this.tabs[index].name} 吗？`,
				success: (res) => {
					if (res.confirm) {
						const deletedTab = this.tabs.splice(index, 1)[0];
						
						// Remove the group from scheduleData
						if (this.scheduleData[this.currentDate]) {
							this.scheduleData[this.currentDate].groups = 
								this.scheduleData[this.currentDate].groups
									.filter(g => g.groupType !== deletedTab.type);
						}
						
						// Adjust activeTab if needed
						if (this.activeTab >= this.tabs.length) {
							this.activeTab = this.tabs.length - 1;
						}
						
						this.updateTabStats();
					}
				}
			});
		}
		}
	};
</script>

<style lang="scss" scoped>
	/* 样式部分保持不变 */
	.tabs {
		display: flex;
		border-bottom: 2rpx solid #eee;
		background-color: #fff;
		position: relative;
		z-index: 10;
	}

	.tab {
		flex: 1;
		text-align: center;
		padding: 24rpx 0;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			color: #007AFF;
			font-weight: 500;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 4rpx;
				background-color: #007AFF;
			}
		}
	}

	.edit-btn {
		padding: 24rpx 30rpx;
		color: #333;
		font-size: 28rpx;
	}
	
	.add-btn {
		padding: 24rpx 30rpx;
		color: #007AFF;
		font-size: 28rpx;
		font-weight: bold;
	}
	
	.group-name {
		margin-right: 8rpx;
	}
	
	.delete-btn {
		color: #ff4949;
		font-size: 32rpx;
		font-weight: bold;
		padding: 0 10rpx;
		border-radius: 50%;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
		line-height: 40rpx;
		vertical-align: middle;
		background-color: #f5f5f5;
	}

	.staff-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(140rpx, 1fr));
		gap: 24rpx;
		padding: 24rpx;
		margin-bottom: 300rpx;

		.staff-btn {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			margin: 0;
			padding: 0;
			border-radius: 12rpx;
			background-color: #f5f5f5;
			color: #333;
			font-size: 24rpx;
			transition: all 0.2s;
			border: none;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;

			&.selected {
				background-color: #007AFF;
				color: #fff;
				transform: scale(1.03);
			}

			&.conflict {
				background-color: #ff4949;
				color: #fff;
				pointer-events: none;
			}
		}
	}

	.footer {
		padding: 20rpx;
		background-color: #fff;
		border-top: 2rpx solid #eee;

		.submit-btn {
			background-color: #007AFF;
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
		}
	}

	.edit-popup {
		background: #fff;
		border-radius: 16rpx;
		width: 600rpx;
		max-width: 90%;
		overflow: hidden;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx 32rpx;
			background: #f8f8f8;
			font-weight: bold;
			font-size: 32rpx;
		}

		.popup-body {
			padding: 32rpx 24rpx;
		}

		.group-input {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;
		}

		.group-label {
			width: 120rpx;
			font-size: 28rpx;
			color: #666;
		}

		.uni-input {
			flex: 1;
			height: 60rpx;
			padding: 0 20rpx;
			border: 2rpx solid #ddd;
			border-radius: 8rpx;
			font-size: 28rpx;
		}

		.popup-footer {
			display: flex;
			justify-content: space-between;
			padding: 0 32rpx 32rpx;
		}

		.btn {
			flex: 1;
			margin: 0 16rpx;
			font-size: 28rpx;
			padding: 16rpx 0;
			border-radius: 8rpx;
		}
	}

	.copy-btn {
		background-color: #007AFF;
		color: #fff;
		font-size: 28rpx;
		padding: 20rpx;
		text-align: center;
		border-radius: 12rpx;
		margin: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.icon-copy {
			margin-right: 10rpx;
		}
	}

	.copy-popup {
		background: #fff;
		border-radius: 16rpx;
		width: 700rpx;
		max-width: 90%;
		overflow: hidden;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx 32rpx;
			background: #f8f8f8;
			font-weight: bold;
			font-size: 32rpx;
		}

		.popup-body {
			padding: 0rpx 0;
			min-height: 600rpx;
		}

		.uni-calendar {
			transform: scale(0.85);
			transform-origin: center top;
		}

		.popup-footer {
			display: flex;
			justify-content: space-between;
			padding: 0 32rpx 32rpx;
		}

		.btn {
			flex: 1;
			margin: 0 16rpx;
			font-size: 28rpx;
			padding: 16rpx 0;
			border-radius: 8rpx;
		}
	}
</style>